/**
 * 字典管理 -  遥调分组 - 列表
 * @author xiaoxujs
 */

import { useCallback, useEffect, useState } from "react";
import { useLocation } from 'react-router-dom'
import { ButtonAddX, ButtonLinkX, ButtonX, Search } from "../../../../components/UiManagement";
import { DicManagedEventBox, Guangdian, RolePageHeaderBox, RolePageListBox } from "./style";
import { IFenye } from "../../../../type/common";
import AddChangeModule from './components/AddChangeModule'; // 新增事件分组弹框
import { PitModal } from '../../../../components/UiManagement'; // 新增事件分组弹框
import PaginationX from "../../../../components/PaginationX";
import { message, Spin, Upload, UploadProps } from "antd";
import { ISyhtDictTelemetryGetDictTelemetryAll } from "../../../../type/ConfigManagement/DicManaged/DicManagedYaoce";
import { IyhtDictTelemetryItemGetDictTelemetryPage, IyhtDictTelemetryItemGetDictTelemetryPageParams } from "../../../../type/ConfigManagement/DicManaged/DicManagedYaoceList";
import { getSyhtDictTelemetryItemDeleteTelemetryItem, postSyhtDictTelemetryItemGetDictTelemetryPage } from "../../../../api/ConfigManagement/DicManaged/DicManagedYaoceListApi";
import { postSyhtDictTelemetryItemGetTelemetryItemExeclUrl, postSyhtDictTelemetryItemGetTelemetryItemTemplateUrl, postSyhtDictTelemetryItemImportDataUrl } from "../../../../api/ConfigManagement/DicManaged/DicManagedYaoceApi";
import { postHandleTemplateDownload } from "../../../../assets/fun/File/fileDownloadFun";
import { handleGetDictionaryItemValue } from "../../../../assets/fun/DictionaryItem";
import { dicInterval } from "../../../../assets/data/dicData";

const DicManagedEventList = () => {
    const location = useLocation() as { state: ISyhtDictTelemetryGetDictTelemetryAll }; // 接收参数

    const [addChangeEventShow, setAddChangeEventShow] = useState(false); // 新增事件弹框
    const [deleteTipModalShow, setDeleteTipModalShow] = useState(false); // 删除提示弹框
    const [listData, setListData] = useState<IyhtDictTelemetryItemGetDictTelemetryPage[]>([]); // 列表数据
    const [searchValue, setSearchValue] = useState<string>(''); // 检索
    const [pading, setPading] = useState({
        size: 10, // 每页条数
        currentPage: 1, // 当前页码
    })
    const [total, setTotal] = useState(0); // 总条数
    const [deleteId, setDeleteId] = useState<string>(); // 点击的ID

    const [spinning, setSpinning] = useState(false); // 加载中
    const listFun = useCallback(
        async (params: IyhtDictTelemetryItemGetDictTelemetryPageParams) => {
            const { code, msg, data } = await postSyhtDictTelemetryItemGetDictTelemetryPage(params) as IFenye<IyhtDictTelemetryItemGetDictTelemetryPage>;
            if (code === 200) {
                setListData(data.records)
                setPading({
                    currentPage: Number(data.current),
                    size: Number(data.size)
                });
                setTotal(Number(data.total))
            } else {
                alert(msg)
            }

        },
        [],
    )

    useEffect(() => {
        const params = {
            size: 10,
            currentPage: 1,
            telemetryId: location.state.telemetryId
        }
        listFun(params)
    }, [listFun, location.state.telemetryId])



    // 检索
    const handleSearch = (value: string) => {
        setSearchValue(value) // 检索
        const params = {
            size: 10,
            currentPage: 1,
            telemetryId: location.state.telemetryId,
            infoName: value
        }
        listFun(params)
    }
    // 新增事件分组弹框回调
    const handleAddChangeModuleCallback = () => {
        setAddChangeEventShow(false) // 关闭弹窗
        setDeleteId(undefined) // 重置
        const params = {
            size: 10,
            currentPage: 1,
            telemetryId: location.state.telemetryId,
        }
        listFun(params)
    }
    // 删除提示弹框回调
    const handleDeletePitCallback = async (type: 'ok' | 'cancel') => {
        if (type === 'ok') {
            if (!deleteId) {
                return alert('请选择要删除的数据')
            }
            const { code, msg } = await getSyhtDictTelemetryItemDeleteTelemetryItem({ TelemetryItemId: deleteId }) as { code: number, msg: string };
            if (code === 200) {
                setDeleteTipModalShow(false) // 关闭弹窗
                setDeleteId(undefined) // 重置
                const params = {
                    size: pading.size,
                    currentPage: pading.currentPage,
                    telemetryId: location.state.telemetryId,
                    infoName: searchValue
                }
                listFun(params) // 刷新列表
            } else {
                alert(msg)
            }
        } else {
            setDeleteTipModalShow(false) // 关闭弹窗
            setDeleteId(undefined) // 重置
        }
    }
    // 删除
    const handleDelete = (item: IyhtDictTelemetryItemGetDictTelemetryPage) => {
        setDeleteTipModalShow(true);
        setDeleteId(item.telemetryItemId);
    }
    // 分页
    const handlePaginationChange = (current: number, pageSize: number) => {
        const params = {
            size: pageSize,
            currentPage: current,
            telemetryId: location.state.telemetryId,
            infoName: searchValue
        }
        listFun(params)
    }
    const props: UploadProps = {
        name: 'file',
        action: postSyhtDictTelemetryItemImportDataUrl,
        maxCount: 0,
        headers: {
            token: sessionStorage.getItem("token")!, // 请求头
            checkType: "ck-token-auth",
        },
        data: { telemetryId: location.state.telemetryId },
        beforeUpload: (file) => {
            console.log(file.type === '')
            const isPNG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (!isPNG) {
                alert(`上传文件格式错误，请上传 .xlsx 格式文件！`);
            }
            return isPNG || Upload.LIST_IGNORE;
        },
        onChange(info) {
            setSpinning(true)
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                const params = {
                    size: 10,
                    currentPage: 1,
                    telemetryId: location.state.telemetryId,
                }
                listFun(params)
                setSpinning(false)
            } else if (info.file.status === 'error') {
                setSpinning(false)
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };
    return (
        <DicManagedEventBox>
            <RolePageHeaderBox>
                <div className="left">
                    <div className="left_left_jiantou"></div>
                    <div>全部列表</div>
                    <div className="left_right_jiantou"></div>
                </div>
                <div className="right">
                    <Search placeholder="请搜索关键字" searchChange={(value) => handleSearch(value)} />
                    <ButtonAddX style={{ marginLeft: '3rem' }} onClick={() => setAddChangeEventShow(true)}  >
                        添加事件
                    </ButtonAddX>
                    <ButtonX style={{ marginLeft: '3rem' }} type="info" onClick={() => {
                        postHandleTemplateDownload(
                            postSyhtDictTelemetryItemGetTelemetryItemTemplateUrl,
                            {},
                            'xlsx',
                            "arraybuffer"
                        )
                    }}>模板下载</ButtonX>
                    <Upload {...props}>
                        <ButtonX style={{ marginLeft: '3rem' }} type="info" onClick={() => { }}>一键导入</ButtonX>
                    </Upload>

                    <ButtonX style={{ marginLeft: '3rem' }} type="info" onClick={() => postHandleTemplateDownload(
                        postSyhtDictTelemetryItemGetTelemetryItemExeclUrl,
                        { telemetryId: location.state.telemetryId, },
                        'xlsx',
                        "arraybuffer"
                    )}
                    >全部导出</ButtonX>
                </div>
            </RolePageHeaderBox>
            <RolePageListBox>
                <table>
                    <thead>
                        <tr>
                            <th><div><Guangdian />地址序号</div></th>
                            <th><div><Guangdian />参数名称</div></th>
                            <th><div><Guangdian />最小值</div></th>
                            <th><div><Guangdian />最大值</div></th>
                            <th><div><Guangdian />精度</div></th>
                            <th><div><Guangdian />数据单位</div></th>
                            <th><div><Guangdian />解析规则</div></th>
                            <th><div><Guangdian />是/否存储</div></th>
                            <th><div><Guangdian />存储间隔</div></th>
                            <th><div><Guangdian />存储周期(天)</div></th>
                            <th><div><Guangdian />操作</div></th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            listData.map((item, index) => <tr key={item.telemetryItemId}>
                                <td><div className="td_div_style">{item.addrNum || '-'}</div></td>
                                <td><div className="td_div_style">{item.paramName || '-'}</div></td>
                                <td><div className="td_div_style">{item.min || '-'}</div></td>
                                <td><div className="td_div_style">{item.max || '-'}</div></td>
                                <td><div className="td_div_style">{item.accuracy || '-'}</div></td>
                                <td><div className="td_div_style">{item.unit || '-'}</div></td>
                                <td><div className="td_div_style">{item.parserRule || '-'}</div></td>
                                <td><div className="td_div_style">{ item.isStore === '0' ? '否' : '是'}</div></td>
                                <td><div className="td_div_style">{ handleGetDictionaryItemValue(dicInterval, String(item.storeInterval))}</div></td>
                                <td><div className="td_div_style">{item.storeDay || '-'}</div></td>
                                <td>
                                    <div className="button">
                                        <ButtonLinkX style={{ marginRight: '1rem' }} onClick={() => {
                                            setDeleteId(item.telemetryItemId);
                                            setAddChangeEventShow(true);
                                        }}>
                                            编辑
                                        </ButtonLinkX>
                                        <ButtonLinkX style={{ marginRight: '1rem' }} onClick={() => handleDelete(item)}>
                                            删除
                                        </ButtonLinkX>
                                    </div>
                                </td>
                            </tr>)
                        }


                    </tbody>
                </table>
                <PaginationX current={pading.currentPage} pageSize={pading.size} total={total} onChange={handlePaginationChange} />
            </RolePageListBox>
            <Spin spinning={spinning}  fullscreen />
            {/* // 新增事件分组弹框 */}
            {
                location.state && <AddChangeModule 
                telemetryId =  {location.state.telemetryId}   
                    open={addChangeEventShow} 
                    onClose={() => handleAddChangeModuleCallback()} 
                    clickId = {deleteId}
                    />
            }
            <PitModal open={deleteTipModalShow} onClose={handleDeletePitCallback} message={"确定要删除当前事件吗"} type={"delete"}></PitModal>
        </DicManagedEventBox>
    )
}

export default DicManagedEventList;